package location

import (
	"context"
	"device-admin/internal/app/grpc/client"
	"device-admin/internal/app/grpc/protoc/system_admin"
	"device-admin/internal/app/web/service/common"
	"device-admin/internal/dal"
	"device-admin/internal/dao"
	"device-admin/internal/models"
	"strings"

	"192.168.1.75/go-pkg/errorx"
	"github.com/mozillazg/go-pinyin"
)

var MallServiceDefault = []models.MallService{
	{
		Name: "广播寻人寻物", Order: 1, Logo: "/device-admin/be-file/assets/mall-service/广播寻人寻物.png", FirstLetter: "gbxrxw", Type: 1,
	},
	{
		Name: "停车服务", Order: 1, Logo: "/device-admin/be-file/assets/mall-service/停车服务.png", FirstLetter: "tcfw", Type: 1,
	},
	{
		Name: "顾客咨询", Order: 1, Logo: "/device-admin/be-file/assets/mall-service/顾客咨询.png", FirstLetter: "gkzx", Type: 1,
	},
	{
		Name: "借用婴儿车", Order: 1, Logo: "/device-admin/be-file/assets/mall-service/借用婴儿车.png", FirstLetter: "jyyec", Type: 1,
	},
	{
		Name: "借用轮椅", Order: 1, Logo: "/device-admin/be-file/assets/mall-service/借用轮椅.png", FirstLetter: "jyly", Type: 1,
	},
	{
		Name: "借用雨伞", Order: 1, Logo: "/device-admin/be-file/assets/mall-service/借用雨伞.png", FirstLetter: "jyys", Type: 1,
	},
	{
		Name: "借用医药箱", Order: 1, Logo: "/device-admin/be-file/assets/mall-service/借用医药箱.png", FirstLetter: "jyyyx", Type: 1,
	},
	{
		Name: "借用针线包", Order: 1, Logo: "/device-admin/be-file/assets/mall-service/借用针线包.png", FirstLetter: "jyzxb", Type: 1,
	},
	{
		Name: "借用花镜", Order: 1, Logo: "/device-admin/be-file/assets/mall-service/借用花镜.png", FirstLetter: "jyhj", Type: 1,
	},
	{
		Name: "借用手机充电宝", Order: 1, Logo: "/device-admin/be-file/assets/mall-service/借用手机充电宝.png", FirstLetter: "jysjcdb", Type: 1,
	},
	{
		Name: "其他事项", Order: 1, Logo: "/device-admin/be-file/assets/mall-service/其他事项.png", FirstLetter: "qtsx", Type: 1,
	},
	{
		Name: "service_floor", Order: 1, Logo: "", Type: 2, // 客服中心所在楼层
	},
}

// MallService 商场服务
type MallService struct{}

// 商场服务开通状态
func (MallService) OpenStatus(ctx context.Context, robotID string, locationID string) int {
	if locationID == "" {
		record, _ := dao.Device{}.Detail(ctx, dal.Q, robotID)
		if record != nil {
			locationID = record.LocationID
		}
	}
	return dao.MallService{}.OpenStatus(ctx, dal.Q, locationID)
}

// OpenList 已开通商场服务的商场
func (MallService) LocationList(ctx context.Context, locationName string, page, limit int) ([]dao.MallServiceLocationList, int64) {
	records, count := dao.MallService{}.LocationList(ctx, dal.Q, locationName, page, limit)
	var areaIDs []string
	for _, record := range records {
		areaIDs = append(areaIDs, record.ProvinceID, record.CityID, record.DistrictID)
	}
	if len(areaIDs) > 0 {
		cli, err := client.GetSystemAdminClient()
		if err == nil {
			rsp, err := cli.AreaName(context.Background(), &system_admin.AreaNameReq{AreaIds: areaIDs})
			if err == nil && rsp != nil {
				for index, record := range records {
					records[index].Province = rsp.AreaNameMap[record.ProvinceID]
					records[index].City = rsp.AreaNameMap[record.CityID]
					records[index].District = rsp.AreaNameMap[record.DistrictID]
				}
			}
		}
	}
	return records, count
}

// Open 开通商场服务
func (MallService) Open(ctx context.Context, locationID string) error {
	records := []*models.MallService{}
	for _, defaultRecord := range MallServiceDefault {
		records = append(records, &models.MallService{
			Name:        defaultRecord.Name,
			Order:       defaultRecord.Order,
			Logo:        defaultRecord.Logo,
			FirstLetter: defaultRecord.FirstLetter,
			Type:        defaultRecord.Type,
			LocationID:  locationID,
		})
	}
	return dao.MallService{}.Add(ctx, dal.Q, records)
}

// Close 关闭商场服务
func (MallService) Close(ctx context.Context, locationID string) error {
	// 判断位置是否存在
	if !(dao.Location{}).Exists(ctx, dal.Q, locationID) {
		return errorx.New("位置不存在")
	}
	return dao.MallService{}.Close(ctx, dal.Q, locationID)
}

// Add 添加服务项
// locationID 商场id
// serviceType 服务类型 1-服务项目 2-客服项目
func (MallService) List(ctx context.Context, robotID, locationID string, serviceType int, status int) []*models.MallService {
	if locationID == "" {
		record, _ := dao.Device{}.Detail(ctx, dal.Q, robotID)
		if record != nil {
			locationID = record.LocationID
		}
	}
	return dao.MallService{}.List(ctx, dal.Q, locationID, serviceType, status)
}

// Add 添加服务项
func (MallService) Add(ctx context.Context, records []*models.MallService) error {
	for _, record := range records {
		// 位置校验
		if !(dao.Location{}).Exists(ctx, dal.Q, record.LocationID) {
			return errorx.New("无效的位置", -1)
		}
		// 服务名称首字母
		if record.Name != "" {
			firstLetters := []string{}
			pys := pinyin.Pinyin(record.Name, pinyin.NewArgs())
			if len(pys) > 0 {
				for _, py := range pys {
					if len(py) > 0 {
						if len(py[0]) > 0 {
							firstLetters = append(firstLetters, string(py[0][0]))
						}
					}
				}
			}
			record.FirstLetter = strings.Join(firstLetters, "")
		}
		// 服务详情文件确认
		if record.Detail != "" {
			record.Detail = common.RichTextConvert(record.Detail)
		}
	}
	return dao.MallService{}.Add(ctx, dal.Q, records)
}

// Update 更新服务项
func (MallService) Update(ctx context.Context, record *models.MallService) error {
	// 服务名称首字母
	if record.Name != "" {
		firstLetters := []string{}
		pys := pinyin.Pinyin(record.Name, pinyin.NewArgs())
		if len(pys) > 0 {
			for _, py := range pys {
				if len(py) > 0 {
					firstLetters = append(firstLetters, py[0])
				}
			}
		}
		record.FirstLetter = strings.Join(firstLetters, "")
	}
	// 服务详情文件确认
	if record.Detail != "" {
		record.Detail = common.RichTextConvert(record.Detail)
	}
	return dao.MallService{}.Update(ctx, dal.Q, record)
}

// Delete 删除服务项
func (MallService) Delete(ctx context.Context, mallServiceID string) error {
	q := dal.Q
	q.Transaction(func(tx *dal.Query) error {
		err := dao.MallService{}.Delete(ctx, tx, mallServiceID)
		if err != nil {
			return err
		}
		err = dao.MallServiceQA{}.Delete(ctx, tx, mallServiceID)
		if err != nil {
			return err
		}
		return nil
	})
	return nil
}

type MallServiceDetailT struct {
	*models.MallService
	Questions []*models.MallServiceQA `json:"questions"`
}

// Detail 商场服务详情
// 包括常见问题
func (MallService) Detail(ctx context.Context, mallServiceID string) MallServiceDetailT {
	res := MallServiceDetailT{}
	// 获取服务详情
	detail, _ := dao.MallService{}.Detail(ctx, dal.Q, mallServiceID)
	// 获取服务常见问题
	qaList, _ := dao.MallServiceQA{}.List(ctx, dal.Q, mallServiceID)
	res.MallService = detail
	if len(qaList) == 0 {
		qaList = []*models.MallServiceQA{}
	}
	res.Questions = qaList
	return res
}

type MallServiceQA struct{}

func (MallServiceQA) Add(
	ctx context.Context,
	serviceID string,
	question string,
	answer string,
) error {
	if !(dao.MallService{}).Exists(ctx, dal.Q, serviceID) {
		return errorx.New("无效的服务项", -1)
	}
	answer = common.RichTextConvert(answer)
	q := dal.Q
	err := q.Transaction(func(tx *dal.Query) error {
		questionID, err := dao.MallServiceQA{}.Add(ctx, tx, serviceID, question, answer)
		if err != nil {
			return err
		}
		err = dao.MallServiceQAKeywords{}.Add(ctx, tx, questionID, question)
		return err
	})
	return err
}

func (MallServiceQA) Update(
	ctx context.Context,
	questionID string,
	question string,
	answer string,
) error {
	answer = common.RichTextConvert(answer)
	return dao.MallServiceQA{}.Update(ctx, dal.Q, questionID, question, answer)
}

func (MallServiceQA) Delete(
	ctx context.Context,
	questionID string,
) error {
	return dao.MallServiceQA{}.Delete(ctx, dal.Q, questionID)
}

func (MallServiceQA) List(
	ctx context.Context,
	serviceID string,
) (records []*models.MallServiceQA, err error) {
	return dao.MallServiceQA{}.List(ctx, dal.Q, serviceID)
}
